package com.polaris.live.im.sfs.processor.impl.system

import androidx.annotation.StringDef
import com.polaris.live.im.sfs.core.bean.DataArgument
import com.polaris.live.im.sfs.core.bean.EventWrapper
import com.polaris.live.im.sfs.processor.AbstractMessageProcessor
import sfs2x.client.core.SFSEvent
import java.util.concurrent.ConcurrentHashMap

/**
 * 监听事件返回
 *
 * @author Created by lucas on 2023/11/8 18:02
 * @since 1.0.0
 */
class EventDeferredMessageProcessor(
    private val eventQueue: ConcurrentHashMap<String, MutableList<EventWrapper>>
) : AbstractMessageProcessor() {

    override fun shouldProcess(type: Int, command: String): Boolean {
        return command in commands
    }

    override suspend fun handle(type: Int, command: String, argument: DataArgument) {
        val list = eventQueue[command] ?: return

        list.forEach {
            if (it.type == type) {
                if (it.condition == null) {
                    it.deferred.complete(argument)
                } else {
                    if (it.condition.test(argument)) {
                        it.deferred.complete(argument)
                    }
                }
            }
        }
    }

    companion object {

        val commands = listOf(
            SFSEvent.ROOM_JOIN,
            SFSEvent.USER_EXIT_ROOM
        )
    }
}

@StringDef(SFSEvent.ROOM_JOIN)
annotation class EventListen
